package com.cats.bi.sqltool.syntax.join;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cats.bi.sqltool.SQLString;
import com.cats.bi.sqltool.basic.AbstractClause;
import com.cats.bi.sqltool.basic.Column;
import com.cats.bi.sqltool.basic.MultiClause;

/**
 * @author wang
 */
public abstract class AbstractJoin<T extends AbstractJoin<T>> implements SQLString {
    private AbstractClause abstractClause;

    public final String type;
    public final Column column;
    public final Column pattern;
    public String select;

    AbstractJoin(String type, Column column, Column pattern) {
        this.type = type;
        this.column = column;
        this.pattern = pattern;
        abstractClause = AbstractClause.eq(column, pattern);
    }

    AbstractJoin(String type, Column column, Column pattern, AbstractClause clause) {
        this.type = type;
        this.column = column;
        this.pattern = pattern;
        abstractClause = AbstractClause.eq(column, pattern).and(clause);
    }

    AbstractJoin(String type, String select, Column column, Column pattern) {
        this.select = select;
        this.type = type;
        this.column = column;
        this.pattern = pattern;
        abstractClause = AbstractClause.eq(column, pattern);
    }

    @Override
    public void toSql(StringBuilder sb) {
        sb.append(type);
        if (StringUtils.isNotBlank(select)) {
            sb.append(select);
            sb.append(") ");
        } else {
            pattern.tableInFrom(sb);
        }
        sb.append(" ON ");
        abstractClause.toSql(sb);
    }

    public T and(AbstractClause abstractClause) {
        this.abstractClause.and(new MultiClause(abstractClause));
        return (T) this;
    }
}